﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using core_bll.Services.Base;
using crm_dal.Objects;
using System.Web.UI;

namespace core_bll.Services
{
	public class SalesReportResponse : ServiceResponse
	{
		public SalesReportResponse(List<Sale> sales)
		{
			//TODO: Set error flag.

			Table table = new Table();

			var userNameLabel = GenerateLiteral("Selling Agent");
			var customerLabel = GenerateLiteral("Customer");
			var totalLabel = GenerateLiteral("Sale Total");
			table.Rows.Add(GenerateTableRow(TableRowSection.TableHeader, userNameLabel, customerLabel, totalLabel));
			
			var totalSales = 0.0M;
			foreach(var sale in sales)
			{
				var userName = GenerateLiteral(sale.UserName);
				var clientName = GenerateLiteral(sale.ClientName);
				var total = GenerateLiteral(sale.TotalStr.ToString());

				table.Rows.Add(GenerateTableRow(TableRowSection.TableBody, userName, clientName, total));

				totalSales += sale.Total;
			}

			var empty = GenerateLiteral("");
			var finalTotal = GenerateLiteral(totalSales.ToString()); // TODO: Currency format here.


			table.Rows.Add(GenerateTableRow(TableRowSection.TableBody, empty, empty, finalTotal));

			this.Contents = table;
		}

		private Literal GenerateLiteral(string str)
		{
			return new Literal{ Text = str };
		}

		public TableRow GenerateTableRow(TableRowSection rowSection, params Control[] ctrls)
		{
			var row = new TableRow { TableSection = rowSection };

			foreach (var ctrl in ctrls)
			{
				if(rowSection == TableRowSection.TableHeader)
					row.Cells.Add(GenerateTableHeaderCell(ctrl));
				else
					row.Cells.Add(GenerateTableCell(ctrl));
			}

			return row;
		}

		public TableCell GenerateTableCell(Control ctrl)
		{
			var cell = new TableCell();

			cell.Controls.Add(ctrl);

			return cell;
		}
		
		public TableHeaderCell GenerateTableHeaderCell(Control ctrl)
		{
			var cell = new TableHeaderCell();

			cell.Controls.Add(ctrl);

			return cell;
		}


		private Control _contents;
		public override Control Contents
		{
			get
			{
				return _contents;
			}
			set
			{
				_contents = value;
			}
		}
	}
}
